<template>
  <ContentBase>
    <div class="row justify-content-md-center" v-if="!$store.state.user.loading_information">
      <div class="col-3">
        <form @submit.prevent="login">
          <div class="mb-3">
            <label for="username" class="form-label">Username:</label>
            <input v-model="username" type="text" class="form-control" id="username" >
          </div>
          <div class="mb-3">
            <label for="password" class="form-label">Password:</label>
            <input v-model="password" type="password" class="form-control" id="password">
          </div>
          <div class="error_message">{{error_message}}</div>
          <button type="submit" class="btn btn-primary">Submit</button>
        </form>
      </div>
    </div>
  </ContentBase>
</template>

<script>
import ContentBase from "@/components/ContentBase";
import {useStore} from 'vuex';
import {ref} from 'vue';
import router from "@/router";
import {ElMessage} from "element-plus";

export default {
  name: "UserAccountLoginView",
  components: {ContentBase},
  setup(){
    const store = useStore();
    let username = ref("");
    let password = ref("");
    let error_message = ref("");


    const jwt_token = localStorage.getItem("JWT_Token");
    if (jwt_token){
      store.commit("updateToken",jwt_token);
      store.dispatch("getInfo",{
        success(){
          router.push({name:"home"});
          store.commit("updateLoadingInformation",false);
        },
        error(){
          store.commit("updateLoadingInformation",false);
        }
      });
    } else {
      store.commit("updateLoadingInformation",false);
    }

    const login = () =>{
        error_message.value = "";
        store.dispatch("login",{
              username:username.value,
              password:password.value,

              success() {
                store.dispatch("getInfo",{
                    success(){
                        ElMessage.success("登录成功")
                        router.push({name:"home"});
                    },
                    error(){
                      console.log("获取信息失败");
                    }
                });
              },
              error(){
                error_message.value = "用户名或密码错误";
              },
        })
    }

    return{
      username,
      password,
      error_message,
      login,


    }
  }
}
</script>

<style scoped>
.btn{
  width: 100%;
}
.error_message{
  color: red;
}
</style>
